package com.hqyj.springBoot.modules.account.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.springBoot.modules.common.vo.Result;
import com.hqyj.springBoot.modules.common.vo.Search;
import com.hqyj.springBoot.modules.account.dao.ResourceDao;
import com.hqyj.springBoot.modules.account.entity.Resource;
import com.hqyj.springBoot.modules.account.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.Optional;

@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceDao resourceDao;

    @Override
    @Transactional
    public Result<Resource> insertResource(Resource resource) {
        Resource temp = resourceDao.selectResourceByPerMission(resource.getPermission());

        if (temp != null){
            return new Result<>(Result.ResultStatus.SUCCESS.code, "Permission is repeat");
        }

        resource.setCreateDate(new Date());
        resourceDao.insertResource(resource);

        return new Result<>(Result.ResultStatus.SUCCESS.code, "Insert success",resource);
    }

    @Override
    @Transactional
    public Result<Resource> updateResource(Resource resource) {

        Resource temp = resourceDao.selectResourceByPerMission(resource.getPermission());
        if (temp !=null && temp.getResourceId() == resource.getResourceId()){
            return new Result<>(Result.ResultStatus.FAILED.code, "ResourceId is repeat",resource);
        }

        resourceDao.updateResource(resource);

        return new Result<>(Result.ResultStatus.SUCCESS.code, "Update success",resource);
    }

    @Override
    @Transactional
    public Result<Object> deleteResourceById(int resourceId) {
        resourceDao.deleteResourceById(resourceId);
        return new Result<>(Result.ResultStatus.SUCCESS.code, "Delete success");
    }

    @Override
    @Transactional
    public Resource selectResourceById(int resourceId) {
        return resourceDao.selectResourceById(resourceId);
    }

    @Override
    @Transactional
    public PageInfo<Resource> getResourcesBySearch(Search search) {
        //初始化search
        search.init();
        //开启分页
        PageHelper.startPage(search.getCurrentPage(),search.getPageSize());

        return PageInfo.of(Optional.ofNullable(resourceDao.getResourcesBySearch(search))
                .orElse(Collections.emptyList()));
    }


}
